<template>
  <div>
    <!-- 左右眼数据分析 -->
    <el-divider> {{ props.title }} </el-divider>
    <div v-if="tableData && tableData.length != 0" class="mb-2">
      <el-alert
        :closable="false"
        v-for="(item, index) in tableData"
        :key="index"
        class="mb-1"
      >
        {{ index + 1 }}. {{ item }}
      </el-alert>
    </div>
    <el-empty
      v-else
      :image-size="60"
      :description="`暂无${props.title}数据分析`"
    ></el-empty>
  </div>
</template>

<script setup>
import { ref, onMounted, watchEffect, onBeforeUnmount } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Decimal from "decimal.js";
import { cloneDeep } from "lodash";
import { useUserStore } from "@/pinia";
import { storeToRefs } from "pinia";
import { watchStorage, setStorageWithEvent } from "@/utils/GlobalMonitoring.js";
import { visionUtils } from "@/utils/vision_utils.js";

onMounted(() => {
  // console.log(props);
  tableData.value = [];
});

const userStore = useUserStore();
const { checkDetailForm } = storeToRefs(userStore);

const emit = defineEmits(["updateText"]);
const props = defineProps({
  title: {
    type: String,
    default: "数据分析",
  },
  capName: {
    type: String,
    default: "Left",
  },
  lowerName: {
    type: String,
    default: "left",
  },
});

const tableData = ref([]);

const deviceResult = ref("");

// 计算
function initData() {
  tableData.value = [];
  for (const key in dataForm.value) {
    // 1.裸眼视力
    if (key == `ucva${props.capName}`) {
      if (!isInRange(dataForm.value[`ucva${props.capName}`], undefined, 5.0)) {
        tableData.value.push(
          ...visionUtils
            .VisionResult(
              {
                [`ucva${props.capName}`]:
                  dataForm.value[`ucva${props.capName}`],
              },
              checkDetailForm.value.age,
              checkDetailForm.value.sex
            )
            .filter(Boolean)
        );
      }
    }
    // 2.球镜
    if (key == `${props.lowerName}_s_avg`) {
      if (
        !isInRange(
          dataForm.value[`${props.lowerName}_s_avg`],
          judgeVision(
            dataForm.value[`${props.lowerName}_s_avg`],
            dataForm.value[`${props.lowerName}_c_avg`]
          )
        )
      ) {
        tableData.value.push(
          ...visionUtils
            .VisionResult(
              {
                [`${props.lowerName}_s_avg`]:
                  dataForm.value[`${props.lowerName}_s_avg`],
              },
              checkDetailForm.value.age,
              checkDetailForm.value.sex
            )
            .filter(Boolean)
        );
      }
    }
    // 3.柱镜
    if (key == `${props.lowerName}_c_avg`) {
      if (
        !isInRange(
          dataForm.value[`${props.lowerName}_c_avg`],
          judgeVision(
            dataForm.value[`${props.lowerName}_s_avg`],
            dataForm.value[`${props.lowerName}_c_avg`]
          )
        )
      ) {
        tableData.value.push(
          ...visionUtils
            .VisionResult(
              {
                [`${props.lowerName}_c_avg`]:
                  dataForm.value[`${props.lowerName}_c_avg`],
              },
              checkDetailForm.value.age,
              checkDetailForm.value.sex
            )
            .filter(Boolean)
        );
      }
    }
    // 4.轴位
    if (key == `${props.lowerName}_a_avg`) {
      if (
        !isInRange(
          dataForm.value[`${props.lowerName}_a_avg`],
          judgeVision(
            dataForm.value[`${props.lowerName}_s_avg`],
            dataForm.value[`${props.lowerName}_c_avg`]
          )
        )
      ) {
        tableData.value.push(
          ...visionUtils
            .VisionResult(
              {
                [`${props.lowerName}_a_avg`]:
                  dataForm.value[`${props.lowerName}_a_avg`],
              },
              checkDetailForm.value.age,
              checkDetailForm.value.sex
            )
            .filter(Boolean)
        );
      }
    }
    // 5.眼压
    if (key == `${props.lowerName}IOPAvg`) {
      if (!isInRange(+dataForm.value[`${props.lowerName}IOPAvg`], 8, 21)) {
        tableData.value.push(
          ...visionUtils
            .IntraocularPressure(
              {
                [`${props.lowerName}IOPAvg`]:
                  dataForm.value[`${props.lowerName}IOPAvg`],
              },
              checkDetailForm.value.age,
              checkDetailForm.value.sex
            )
            .filter(Boolean)
        );
      }
    }

    // 1.角膜曲率K1
    if (key == `AxialRatio${props.capName}1`) {
      if (
        !isInRange(
          extractDiopterValue(dataForm.value[`AxialRatio${props.capName}1`]),
          41,
          43
        )
      ) {
        visionUtils
          .BiometricMeasurement(
            {
              [`AxialRatio${props.capName}1`]:
                dataForm.value[`AxialRatio${props.capName}1`],
            },
            checkDetailForm.value.age,
            checkDetailForm.value.sex
          )
          .forEach((item) => {
            if (item[`AxialRatio${props.capName}1`]) {
              tableData.value.push(item[`AxialRatio${props.capName}1`]);
            }
          });
      }
    }
    // 2.角膜曲率K2
    if (key == `AxialRatio${props.capName}2`) {
      if (
        !isInRange(
          extractDiopterValue(dataForm.value[`AxialRatio${props.capName}2`]),
          41,
          43
        )
      ) {
        visionUtils
          .BiometricMeasurement(
            {
              [`AxialRatio${props.capName}2`]:
                dataForm.value[`AxialRatio${props.capName}2`],
            },
            checkDetailForm.value.age,
            checkDetailForm.value.sex
          )
          .forEach((item) => {
            if (item[`AxialRatio${props.capName}2`]) {
              tableData.value.push(item[`AxialRatio${props.capName}2`]);
            }
          });
      }
    }
    //3.角膜散光AST
    if (key == `${props.lowerName}_c_avg`) {
      if (
        !isInRange(
          extractDiopterValue(dataForm.value[`${props.lowerName}_c_avg`], 2),
          -0.5
        )
      ) {
        visionUtils
          .BiometricMeasurement(
            {
              [`${props.lowerName}_c_avg`]:
                dataForm.value[`${props.lowerName}_c_avg`],
            },
            checkDetailForm.value.age,
            checkDetailForm.value.sex
          )
          .forEach((item) => {
            if (item[`${props.lowerName}_c_avg`]) {
              tableData.value.push(item[`${props.lowerName}_c_avg`]);
            }
          });
      }
    }
    // 4.角膜厚度CCT
    if (key == `${props.lowerName}Cct`) {
      if (!isInRange(dataForm.value[`${props.lowerName}Cct`], 0.5, 0.6)) {
        visionUtils
          .BiometricMeasurement(
            {
              [`${props.lowerName}Cct`]:
                dataForm.value[`${props.lowerName}Cct`],
            },
            checkDetailForm.value.age,
            checkDetailForm.value.sex
          )
          .forEach((item) => {
            if (item[`${props.lowerName}Cct`]) {
              tableData.value.push(item[`${props.lowerName}Cct`]);
            }
          });
      }
    }
    // 5.前方深度AD
    if (key == `${props.lowerName}Ad`) {
      if (!isInRange(dataForm.value[`${props.lowerName}Ad`], 2.5, 3.5)) {
        visionUtils
          .BiometricMeasurement(
            {
              [`${props.lowerName}Ad`]: dataForm.value[`${props.lowerName}Ad`],
            },
            checkDetailForm.value.age,
            checkDetailForm.value.sex
          )
          .forEach((item) => {
            if (item[`${props.lowerName}Ad`]) {
              tableData.value.push(item[`${props.lowerName}Ad`]);
            }
          });
      }
    }
    // 6.晶体厚度LT
    if (key == `${props.lowerName}Lt`) {
      if (!isInRange(dataForm.value[`${props.lowerName}Lt`], 3.5, 4)) {
        visionUtils
          .BiometricMeasurement(
            {
              [`${props.lowerName}Lt`]: dataForm.value[`${props.lowerName}Lt`],
            },
            checkDetailForm.value.age,
            checkDetailForm.value.sex
          )
          .forEach((item) => {
            if (item[`${props.lowerName}Lt`]) {
              tableData.value.push(item[`${props.lowerName}Lt`]);
            }
          });
      }
    }
    // 7.眼轴长度
    if (key == `Al${props.capName}`) {
      if (!isInRange(dataForm.value[`Al${props.capName}`], 22.51, 24.63)) {
        visionUtils
          .BiometricMeasurement(
            {
              [`Al${props.capName}`]: dataForm.value[`Al${props.capName}`],
            },
            checkDetailForm.value.age,
            checkDetailForm.value.sex
          )
          .forEach((item) => {
            if (item[`Al${props.capName}`]) {
              tableData.value.push(item[`Al${props.capName}`]);
            }
          });
      }
    }
    // 8.轴率比AL/CR
    if (key == `AxialRatio${props.capName}`) {
      if (
        !isInRange(
          dataForm.value[`AxialRatio${props.capName}`],
          visionUtils.AlCJudge(checkDetailForm.value.age),
          visionUtils.AlCJudge(checkDetailForm.value.age)
        )
      ) {
        visionUtils
          .BiometricMeasurement(
            {
              [`AxialRatio${props.capName}`]:
                dataForm.value[`AxialRatio${props.capName}`],
            },
            checkDetailForm.value.age,
            checkDetailForm.value.sex
          )
          .forEach((item) => {
            if (item[`AxialRatio${props.capName}`]) {
              tableData.value.push(item[`AxialRatio${props.capName}`]);
            }
          });
      }
    }
  }

  tableData.value.forEach((item) => {
    deviceResult.value += item + " ";
  });
  // console.log(deviceResult.value);
  emit("updateText", {
    type: props.lowerName,
    text: deviceResult.value,
  });
}
/**
 * 从角膜曲率数据格式中提取度数数值
 * @param {string} input - 输入字符串，格式如 "7.88/42.75D@175°"
 * @returns {string|null} - 提取的度数数值（如 "42.75"），若格式不匹配则返回 null
 */
function extractDiopterValue(input, type = 1) {
  if (typeof input !== "string") return null;

  // 使用正则表达式匹配中间的度数部分
  if (type == 1) {
    const regex = /\/(\d+(?:\.\d+)?)/;
    const match = input.match(regex);

    return match ? match[1] : null;
  } else if (type == 2) {
    const regex = /^([+-]?\d+(?:\.\d+)?)/;
    const match = input.match(regex);

    return match ? match[1] : null;
  }
}

/**
 * 灵活比较值是否在指定范围内
 * @param {number|string} val - 需要检查的值
 * @param {number|string|undefined} minVal - 区间最小值（可选）
 * @param {number|string|undefined} maxVal - 区间最大值（可选）
 * @returns {boolean} - 根据比较结果返回true或false
 */
function isInRange(val, minVal, maxVal) {
  const numVal = parseFloat(val);

  // 检查val是否为有效数字
  if (isNaN(numVal)) return true;

  // 仅minVal存在
  if (minVal !== undefined && maxVal === undefined) {
    const numMin = parseFloat(minVal);
    return !isNaN(numMin) && numVal >= numMin;
  }

  // 仅maxVal存在
  if (maxVal !== undefined && minVal === undefined) {
    const numMax = parseFloat(maxVal);
    return !isNaN(numMax) && numVal <= numMax;
  }

  // 两者都存在或都不存在
  const numMin = parseFloat(minVal);
  const numMax = parseFloat(maxVal);

  // 两者都不存在时返回true
  if (isNaN(numMin) && isNaN(numMax)) return true;

  // 仅一个有效时按单侧比较
  if (!isNaN(numMin) && isNaN(numMax)) return numVal >= numMin;
  if (!isNaN(numMax) && isNaN(numMin)) return numVal <= numMax;

  // 两者都有效时按双侧比较
  return numVal >= numMin && numVal <= numMax;
}

/**
 * @param {number} sm - 球镜
 * @param {number} cm - 柱镜
 * @returns {Number} - 范围结果
 */
function judgeVision(sm = "0", cm = "0") {
  // 处理除数为0的情况
  if (new Decimal(+cm).eq(0)) {
    return new Decimal(0);
  }
  return new Decimal(+sm).plus(1).dividedBy(new Decimal(2).times(+cm));
}

const dataForm = ref({});

let cleanup;
onMounted(() => {
  cleanup = watchStorage("refresh_region_data", (e) => {
    dataForm.value = {
      ...e.data.vision_data,
      ...e.data.computer_optometry_data,
      ...e.data.iop_data,
      ...e.data.od_os_data,
      ...e.data.subjectivity_data,
      ...e.data.optometrist_query_data,
      ...e.data.visual_function_niu_data,
    };
    initData();
  });
  return () => cleanup();
});

onBeforeUnmount(() => {
  cleanup();
});
</script>

<style scoped lang="scss">
</style>